﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using twlib;

namespace TeamWork_Client
{
    public partial class RCon : Form
    {
        public string ssa = "", si, ci, ip, password;
        public long mkey;

        public RCon(string sub_ser_addr, string sub_id, string coder_id, long mk)
        {
            InitializeComponent();
            ssa = sub_ser_addr;
            si = sub_id;
            ci = coder_id;
            mkey = mk;
            Authorize();
        }

        public RCon(string sub_ser_addr, string sub_id, string coder_id, long mk, bool a)
        {
            InitializeComponent();
            ssa = sub_ser_addr;
            si = sub_id;
            ci = coder_id;
            mkey = mk;
        }

        public void Log(string e)
        {
            StringBuilder strb = new StringBuilder();
            strb.Append(textBox1.Text);
            strb.AppendLine("] " + e);
            textBox1.Text = strb.ToString();
        }

        public bool coder_accepted = false;
        public bool subscription_accepted = false;

        public bool Authorize()
        {
            Log("Contacting subscription services...");
            long p = mkey;

            UserCommand cmd1 = new UserCommand("/checksub", new string[] { si }, p);

            Q1.RRR.BasicQ1BinaryFormation bfmt = new Q1.RRR.BasicQ1BinaryFormation();
            byte[] bts1 = bfmt.Patch(Serialization.BinarySerialize(cmd1));
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(IPAddress.Parse(ssa), 5522);

            s.Send(bts1);

            Log("Checking subscription id...");
            byte[] rcv = new byte[1024];
            s.Receive(rcv);
            ServerResponse res = (ServerResponse)Serialization.BinaryDeserialize(bfmt.DePatch(rcv));
            if (res.OK)
            {
                Log("Subscription ID has been vailidated.");
                Log("Server IP Address is: " + res.ResponseString);
                ip = res.ResponseString;
                subscription_accepted = true;
            }
            else
            {
                Log("Error: " + res.ResponseString);
                return false;
            }

            s.Shutdown(SocketShutdown.Both);
            s.Disconnect(false);
            return true;

            if (ci.Length > 0)
            {
                Log("Checking coder id...");
                UserCommand cmd2 = new UserCommand("/checkcoder", new string[] { ci }, p);

                byte[] bts2 = bfmt.Patch(Serialization.BinarySerialize(cmd2));
                Socket s2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s2.Connect(IPAddress.Parse(ssa), 5522);

                s2.Send(bts2);

                byte[] rcv2 = new byte[1024];
                s2.Receive(rcv);
                ServerResponse res2 = (ServerResponse)Serialization.BinaryDeserialize(bfmt.DePatch(rcv));
                if (res2.OK)
                {
                    Log("Coder ID has been vailidated.");
                    subscription_accepted = true;
                    return true;
                }
                else
                {
                    Log("Error: " + res2.ResponseString);
                    return false;
                }
            }
            return false;
        }

        public string SendCmd(string cmd, bool isSingleArg)
        {
            Log(cmd);
            if (cmd == "/exit")
            {
                Application.Exit();
            }
            if (cmd == "/vclient")
            {
                new Form1(this).Show();
                return "";
            }
            if (cmd == "/hide")
            {
                this.Hide();
                return "";
            }
            if (password == null)
            {
                Log("Error: Please enter the password for the RCON functionality." + Environment.NewLine + "Type: /password [numerical_password].");
                return "";
            }
            long pass = long.Parse(password);
            string[] c_data = cmd.Split(' ');
            UserCommand u_cmd;
            if(!isSingleArg)
                u_cmd = new UserCommand(c_data[0], c_data[1].Split('='), pass);
            else
                u_cmd = new UserCommand(cmd, new string[] {}, pass);
            Q1.RRR.BasicQ1BinaryFormation bfmt = new Q1.RRR.BasicQ1BinaryFormation();

            byte[] bts = bfmt.Patch(Serialization.BinarySerialize(u_cmd));
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(IPAddress.Parse(ip), 5520);

            s.Send(bts);

            byte[] recv = new byte[1024];
            s.Receive(recv);
            ServerResponse res = (ServerResponse)Serialization.BinaryDeserialize(bfmt.DePatch(recv));
            if (!res.OK && res.ResponseString == "")
                Log("Unknown Error. 0x0125fa5");
            Log(res.ResponseString);
            return res.ResponseString;
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (textBox2.Text.Contains("/password"))
                {
                    password = textBox2.Text.Replace("/password ", "");
                    Log("RCon Password Has Been Set To: '" + password + "'.");
                    textBox2.Text = "";
                    return;
                }
                SendCmd(textBox2.Text, (textBox2.Text.Contains("=") ? false : true));
                textBox2.Text = "";
                return;
            }
        }
    }
}
